import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken, getTimeStamp } from '@/utils/auth'
const TimeOut = 3600
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // 只有在有token的情况下 才有必要去检查时间戳是否超时
      if (isCheckTimeOut()) {
        // 如果它为true表示 过期了
        // token没用了 因为超时了
        store.dispatch('user/logout')
        router.push('/login')
        return Promise.reject(new Error('网络连接超时'))
      }
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const { success, message, data, code } = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (success) {
      return data
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;

    } else {
      if (code === 10002) {
        // to re-login
        /*         MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
                  confirmButtonText: 'Re-Login',
                  cancelButtonText: 'Cancel',
                  type: 'warning'
                }).then(() => {
                  store.dispatch('user/resetToken').then(() => {
                    location.reload()
                  })
                }) */
        // 当等于10002的时候 表示 后端告诉我token超时了
        store.dispatch('user/logout') // 登出action 删除token
        router.push('/login')
        return Promise.reject(new Error('网络连接超时'))
      } else {
        Message.error(message)
      }
      return Promise.reject(new Error(message || 'Error'))
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

// 是否超时
// 超时逻辑  (当前时间  - 缓存中的时间) 是否大于 时间差
const isCheckTimeOut = () => {
  const nowTime = Date.now();
  const timeStamp = getTimeStamp();
  return (nowTime - timeStamp) / 1000 > TimeOut
}
export default service
